<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once("Core.php");
class CI_System extends CI_Core{
	function __construct(){
		parent::__construct();
		$this->database('default');
	}
	//获取快递公司列表 
	public function carrier($pc=false){
		$f = (!$pc?'../':'').'uploads/file/delivery.json';
		
		$j = file_get_contents($f);
		return $this->status(true,json_decode($j,true));
	}
	//地区列表
	public function area($force=false,$a=false){
		$f = $a?'uploads/file/area.txt':'../uploads/file/area.txt';
		$j = file_get_contents($f);
		if($j && !$force){
			return $this->status(true,json_decode($j,true));
		}else{
			$items = $this->get_all('*',array(),'area'); 
			foreach($items as $k=>$v){//省
				if($v['pid']==0){
					$arr[$k]=$v;
					foreach($items as $i=>$s){//市
						if($s['pid']==$v['id']){
							$arr[$k]['childs'][$i]=$s;
							foreach($items as $t=>$y){//区
								if($y['pid']==$s['id']){
									$arr[$k]['childs'][$i]['childs'][$t]=$y;
								}
							}
						}
					}
				}
			}
			file_put_contents($f,json_encode($arr));
			return $this->status(true,$arr);
		}
	}
	//获取地区联动
	public function areaList(){
		$pid = $this->ci->input->get('pid');
		$self = $this->ci->input->get('self');
		$params = array('pid'=>empty($pid)?"'0'":$pid);
		if($self) $params['id !=']=$self;
		$arr = $this->get_all('*',$params,'area');
		$rs=array();
		foreach($arr as $v){
			$a = $this->get_all('*',array('pid'=>$v['id']),'area');
			$rs[]=array(
				'id'=>$v['id'],
				'label'=>$v['title'],
				'branch'=>array(),
				'inode'=>count($a)>0?true:false,
				'type'=>'',
			);
		}
		return $this->status(true, $rs);
	}
	function get_city(){
		$arr=$this->get_all('*',array('pid'=>"'0'"),'area');
		foreach($arr as $v){
			$a[$v['title']]=array('id'=>$v['id'],'root'=>0,'djd'=>1);
			$b=$this->get_all('*',array('pid'=>$v['id']),'area');
			foreach($b as $s) $c[$v['id']][]=array('id'=>$s['id'],'name'=>$s['title']);
		}
		$data['province']=json_encode($a);
		$data['city']=json_encode($c);
		return $this->status(true,$data);
	}
	public function get_area(){
		$pid=$this->ci->input->get('fid');
		$callback=$this->ci->input->get('callback');
		$arr=$this->get_all('*',array('pid'=>$pid),'area');
		foreach($arr as $v) $data[]=array('id'=>$v['id'],'name'=>$v['title']);
		return $this->status(true,$data);
		
	}
	//获取区域详情
	public function getArea($id){
		$rs = $this->get_one('*',array('id'=>$id),'area');
		return $this->status(true,$rs);
	}
	//保存地区
	public function saveArea($row){
		$this->write($row,'area');
		return $this->area('../');
	}
	//保存运费
	public function saveShipBill($row){
		$this->write($row,'shipbill');
	}
	//获取运费列表
	public function getShipBill($tj=array(),$tj2=array(),$web='admin',$pagesize=12,$page=1){
		$this->open('shipbill');
		$data=$web=='admin'? $this->get_list($tj,$tj2):$this->front_get_list($tj,$tj2,$pagesize,$page);
		$arr=array();
		foreach($data['result'] as $v){
			$arr[]=$v;
		}
		$rs = array('total'=>$data['total_rows'],'rows'=>$arr);
	    return $this->status(true, $rs);
	}
	//更新运费
	public function shipInfo($id){
		$id=$id?$id:$this->ci->input->get('id');
		$rs=$this->get_one('*',array('id'=>$id),'shipbill');
		return $this->status(true, $rs);
	}
	
	//计算运费NEW
	public function countShip($data_a,$city='北京市',$uid){
		if($data_a){
			$arr=json_decode($data_a,true);
			foreach($arr as $v){
				$g=$this->get_one('*',array('id'=>$v['id']),'goods');
				if($v['format']){
					$gp=$this->get_one('*',array('id'=>$v['format']),'goods_price');
					$rs[]=array(
						'id'=>$g['id'],
						'gnum'          =>$v['amount'],
						'price'         =>$gp['price'],
						'weight'        =>$g['weight'],
						'is_ship_free'  =>$g['is_ship_free'],
						'ship_mode'     =>$g['ship_mode'],
						'universe'      =>$g['universe'],
						'ship_template' =>$g['ship_template'],
					);
				}else{
					$rs[]=array(
						'id'=>$g['id'],
						'gnum'          =>$v['amount'],
						'price'         =>$g['price'],
						'weight'        =>$g['weight'],
						'is_ship_free'  =>$g['is_ship_free'],
						'ship_mode'     =>$g['ship_mode'],
						'universe'      =>$g['universe'],
						'ship_template' =>$g['ship_template'],
					);
				}
			}
			$u=array();
			foreach($rs as $k=>&$e){
				$name=&$e['id'];
				if(!isset($u[$name])){
					$u[$name]=$e;
				}else{
					$u[$name]['gnum']+=$e['gnum'];
					$u[$name]['price']+=$e['price'];
				}
			}
			$rs=array_values($u); unset($u);
		}else{
			$tj2=array(
				'join'=>'goods',
				'on'=>'b.goods_id=a.id',
				'a_fields'=>'sum(goods_amount) as gnum,a.id,a.title,a.price,a.pictures,a.weight,a.is_ship_free,a.ship_mode,a.universe,a.ship_template',
				'group'=>array('goods_id'));
			$rs=$this->get_all('*',array('user_id'=>$uid,'status'=>1),'shopcart',$tj2);
		}
		$ship=0;
		$data['post']=0;$data['express']=0; $data['ems']=0;
		foreach($rs as $v){
			$freeShip=false; $areaStatus=false;//区域是否包含在已设置区域默认FALSE
			if($v['is_ship_free']==1){//卖家承担运费
				$ship+=0;
			}else{ //需要运费
				if($v['ship_mode']==1){ //全国统一运费
					$f=json_decode($v['universe'],true);
					$ship+=$f['express'];
				}else{ //运费模板
					$s=$this->get_one('*',array('id'=>$v['ship_template']),'goods_ship'); //获取商品对应的运费模板
					if($s!=array()){
						$qy=json_decode($s['rules'],true);
						foreach($qy as $k=>$u){
							$ship=0;
							foreach($u as $t){ //区域运费
								$areas = explode(',', $t['area']);
								if(in_array($city,$areas)){
									$areaStatus=true;
									$dqArr=$t;
									break;
								}else if(in_array('ALL',$areas)){
									$areaStatus=false;
									$dqArr=$t;
								}
							}
							if($dqArr['free_tj']==2){ //计算是否免费邮费
								if($dqArr['free_type']==1){ //按金额计算超过X元免运费
									if(($v['price']*$v['gnum'])>$dqArr['free_total']){ //订单金额大于免运费金额
										$ship+=0;
										$freeShip=true;
									}else{
										$freeShip=false;
									}
								}else if($dqArr['free_type']==2){ //按重量计算超过Xkg免运费
									if($v['weight']*$v['gnum']>$dqArr['free_weight']){ //订单重量大于免运费重量
										$ship+=0;
										$freeShip=true;
									}else{
										$freeShip=false;
									}
								}else if($dqArr['free_type']==3){ //按金额+重量计算超过X元Xkg免运费
									if($v['price']*$v['gnum']>$dqArr['free_total'] && $v['weight']*$v['gnum']>$dqArr['free_weight']){ //订单金额大于免运费金额并大于重量
										$ship+=0;
										$freeShip=true;
									}else{
										$freeShip=false;
									}
								}
							}
							if(!$freeShip){
								if($s['ship_mode']==1){ //按件数
									if($v['gnum']==1){ //一件商品处理
										$ship+=$dqArr['firstBill'];
									}else{  //多件商品处理
										$ship+=$dqArr['firstBill'];
										$ship+=($v['gnum']-1)*$dqArr['followBill'];
									}
								}else if($s['ship_mode']==2){ //按重量
									if($v['weight']<=1){ //一件商品处理
										$ship+=$dqArr['firstBill'];
									}else{  //多件商品处理
										$ship+=$dqArr['firstBill'];
										$ship+=($v['gnum']-1)*$dqArr['followBill'];
									}
								}else if($s['ship_mode']==3){ //按体积
							
								}
							}
							if($k=='post') $data['post']+=$ship;
							if($k=='express') $data['express']+=$ship;
							if($k=='ems') $data['ems']+=$ship;
						}
					}
				}
			}
		}
		
		//print_r($data);
		return $this->status(true,$data);
	}
	//计算运费(区域ID,总价,数量,单品重量)
	public function calculateShipFee($areaId,$total,$amount,$weight){
		$arr = $this->get_all('*',array(),'shipbill');
		$fee = 0;
		foreach($arr as $v){
			if(!$v['area_list']) break;
			$area_ids = array_map(create_function('$v', 'return $v["id"];'),json_decode($v['area_list'],true));
			if(in_array($areaId,$area_ids)){
				if($total>=$v['free_total']){//如果达到免费额度
					$fee=0;
					break;
				}
				if($total<$v['lowest_total']){//如果金额小于最低额度
					$fee=$v['lowest_fee'];
					break;
				}
				
				if($v['cal_type']==1){//按件数
					$fee=$v['piece_bill']*$amount;
					break;
				}else{//按重量
					if($weight<1000) $fee=$v['pack_onekg'];
					else $fee=$v['pack_onekg']+($weight-1000)*$v['pack_increment'];
					break;
				}
				break;
			}
		}
		return $this->status(true,$fee);
	}
	//基础设置
	public function settings($s=true){
		$f=$s?'uploads/file/setting.php':'static/data/setting.php';
		if(!file_exists($f)) file_put_contents($f,"<?php\r\n");
		include($f);
		$ENV['stats_code']=htmlspecialchars_decode($ENV['stats_code']);
		return $this->status(true, $ENV);
	}
	//保存基础设置
	public function savebasic(){
		$f = '../uploads/file/setting.php';
		if(!file_exists($f)) file_put_contents($f,"<?php\r\n");
		include($f);
		$arr = $ENV?$ENV:array();
		foreach($_POST as $k=>$v) $arr[$k]=$v;
		//开启流量统计
		if($arr['51lauser'] && $arr['51lapass'] && !$arr['stats_id'] && !$arr['stats_code']){
			$this->ci->load->library('Huashang/statistics');
			$rs = array_pop($this->ci->statistics->addSite(iconv("UTF-8","gbk//TRANSLIT",$arr['title']), str_replace('/admin','',WEB)));
			$arr['stats_id']=$rs['id'];
			$arr['stats_code']=htmlspecialchars($rs['code']);
		}
		foreach($arr as $k=>$v) $a[]='$ENV["'.$k.'"] = "'.str_replace('"','\"',$v).'";';
		file_put_contents($f, "<?php\r\n".implode("\r\n",$a)); 
		exit('{"status":"OK","msg":"执行成功"}');
	}
	// 获取支付方式
	public function getPayments($method='',$domain){
		$c = file_get_contents($domain.'uploads/file/payments.json');
		if(empty($method)){
			return $this->status(true, array('list'=>json_decode(file_get_contents('static/data/payments.json'),true),'rs'=>json_decode($c,true)));
		}else{
			$arr=json_decode($c,true);
			foreach($arr as $v){
				if($v['method']==$method){
					return $this->status(true, json_decode($v['config'],true));
				}
			}
		}
		return $this->status(false);
	}
	//保存支付方式
	public function savePayments($data){
		file_put_contents('../uploads/file/payments.json',$data);
		return $this->status(true);
	}
	
}